﻿/****************************************************************
* MACHINE: DESKTOP-I6HF1HG
* NAME: gjp
* CREATEDATE: 2019/3/13 9:51:06
* DESC: <DESCRIPTION>
* **************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using LEE.Tools.Data;

namespace LEE.Tools.IO
{
    /// <summary>
    /// Summary description for CsvHelper
    /// </summary>
    public static class CsvHelper
    {
        public static byte[] ToCsvData<T>(this List<T> list) where T : class
        {
            var dt = list.ToDataTable();
            byte[] result = null;
            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    var data = "";
                    //写出列名称
                    for (var i = 0; i < dt.Columns.Count; i++)
                    {
                        data += dt.Columns[i].ColumnName;
                        if (i < dt.Columns.Count - 1)
                        {
                            data += ",";
                        }
                    }
                    sw.WriteLine(data);
                    //写出各行数据
                    for (var i = 0; i < dt.Rows.Count; i++)
                    {
                        data = "";
                        for (var j = 0; j < dt.Columns.Count; j++)
                        {
                            var str = dt.Rows[i][j].ToString();
                            str = str.Replace("\"", "\"\""); //替换英文冒号 英文冒号需要换成两个冒号
                            if (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n")) //含逗号 冒号 换行符的需要放到引号中
                            {
                                str = $"\"{str}\"";
                            }

                            data += str;
                            if (j < dt.Columns.Count - 1)
                            {
                                data += ",";
                            }
                        }
                        sw.WriteLine(data);
                    }
                }

                result = ms.ToArray();

            }

            return result;

        }
    }
}
